import axios from "axios";
import { MessageBox,Message }from "element-ui";
import store from "../store";
import { getToken } from "./auth";
// 创建axios实例
const service =axios.create({
  baseURL:process.env.VUE_APP_BASE_API,// url基础地址，解决不同数据源url变化问题
  //withcredentials:true，// 跨域时若要发送cookies需设置该选项
  timeout:5000  //超时
 }); 

 //请求拦截器
 service.interceptors.request.use(
  config=>{
    if(store.getters.token){
      config.headers['X-Token']=getToken()
    }
    return config
  },
  error=>{
    console.log(error)
    return Promise.reject(error)
  }
 )

 //响应拦截器
 service.interceptors.response.use(
  response=>{
    const res=response.data
    if(res.code!==1){
      Message({
        message:res.message||'Error',
        type:'error',
        duration:5*1000
      })
      //假设：50008:非法的token;50012:其他客户端登录了;50014:Token过期;
      if(res.code===50008||res.code===50012||res.code===50014){
        MessageBox.confirm(
            '登录状态异常，请重新登录',
            '确认登录信息',
            {
              confirmButtonText:'重新登录',
              cancelButtonText:'取消',
              type:'warning'
            }
          ).then(()=>{
            store.dispatch('user/resetToken').then(()=>{
              location.reload()
            })
            })
      }
      return Promise.reject(new Error(res.message||'Error'))
      }else{
        return res
      }
  }, 
  error=>{
      Message({
        message:error.message,
        type:'error',
        duration:5*1000
      });
      return Promise.reject(error)
  }
 )
 
 export default service